package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.AlbumMapper;
import com.styletransfer.mapper.CommentMapper;
import com.styletransfer.mapper.UserMapper;
import com.styletransfer.mapper.WorkMapper;
import com.styletransfer.model.*;
import com.styletransfer.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 评论服务类
 *
 * 提供评论相关的业务逻辑处理
 */
@Service
public class CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private NotificationService notificationService;

    /**
     * 添加评论
     *
     * @param comment 评论对象
     * @return API响应
     */
    @Transactional
    public ApiResponse<Comment> addComment(Comment comment) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        User user = userMapper.findById(userId);
        comment.setUserId(userId);

        // 根据评论类型进行不同处理
        String commentType = comment.getType();
        if (commentType == null) {
            commentType = "work"; // 默认为作品评论
        }

        // 检查目标是否存在
        if ("album".equals(commentType)) {
            // 专辑评论
            Album album = albumMapper.findById(comment.getWorkId());
            if (album == null) {
                throw new BusinessException("专辑不存在");
            }
        } else {
            // 作品评论（默认）
            Work work = workMapper.findById(comment.getWorkId());
            if (work == null) {
                throw new BusinessException("作品不存在");
            }
        }

        // 检查评论内容
        if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
            throw new BusinessException("评论内容不能为空");
        }

        // 设置默认值
        comment.setType(commentType);
        comment.setCreateTime(new Date());
        comment.setAvatar(user.getAvatar());
        comment.setNickname(user.getNickname());
        comment.setUsername(user.getUsername());
        comment.setUpdateTime(new Date());
        comment.setStatus(1); // 1:正常, 0:删除

        // 插入评论
        commentMapper.insert(comment);

        // 根据评论类型更新评论数并发送通知
        if ("album".equals(commentType)) {
            // 更新专辑评论数
            albumMapper.incrementCommentCount(comment.getWorkId());
            // 获取专辑信息用于通知
            Album album = albumMapper.findById(comment.getWorkId());
            if (album != null) {
                // 创建专辑评论通知
                notificationService.createNewCommentNotification("new_album",
                    album.getId(),
                    album.getTitle() != null ? album.getTitle() : "专辑",
                    comment.getId(),
                    comment.getContent(),
                    userId,
                    album.getUserId()
                );
            }
        } else {
            // 更新作品评论数
            workMapper.incrementCommentCount(comment.getWorkId());
            // 获取作品信息用于通知
            Work work = workMapper.findById(comment.getWorkId());
            if (work != null) {
                // 创建作品评论通知
                notificationService.createNewCommentNotification("new_work",
                    work.getId(),
                    work.getTitle() != null ? work.getTitle() : "作品",
                    comment.getId(),
                    comment.getContent(),
                    userId,
                    work.getUserId()
                );
            }
        }

        return ApiResponse.success(comment);
    }

    /**
     * 删除评论
     *
     * @param id 评论ID
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> deleteComment(Long id) {
        // 检查评论是否存在
        Comment comment = commentMapper.findById(id);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }

        // 检查是否有权限删除
        if (!isAdmin() && !comment.getUserId().equals(getCurrentUserId())) {
            throw new BusinessException("没有权限删除此评论");
        }

        // 更新评论状态为已删除
        commentMapper.updateStatus(id, 0);

        // 根据评论类型更新评论数
        String commentType = comment.getType();
        if ("album".equals(commentType)) {
            // 更新专辑评论数
            albumMapper.decrementCommentCount(comment.getWorkId());
        } else {
            // 更新作品评论数（默认）
            workMapper.decrementCommentCount(comment.getWorkId());
        }

        return ApiResponse.success();
    }

    /**
     * 根据作品ID查询评论列表
     *
     * @param workId 作品ID
     * @return API响应
     */
    public ApiResponse<List<Comment>> findByWorkId(Long workId) {
        // 检查作品是否存在
        if (workMapper.findById(workId) == null) {
            throw new BusinessException("作品不存在");
        }

        List<Comment> comments = commentMapper.findByWorkId(workId);
        return ApiResponse.success(comments);
    }

    /**
     * 根据作品ID分页查询评论列表
     *
     * @param workId 作品ID
     * @param pageRequest 分页请求
     * @return 分页响应
     */
    public PageResponse<Comment> findByWorkIdWithPage(Long workId, PageRequest pageRequest) {
        // 检查作品是否存在
        if (workMapper.findById(workId) == null) {
            throw new BusinessException("作品不存在");
        }

        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<Comment> comments = commentMapper.findByWorkIdWithPage(workId, offset, pageRequest.getPageSize());
        Long total = commentMapper.countByWorkId(workId);

        // 构建分页响应
        return new PageResponse<>(comments, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }

    /**
     * 根据用户ID查询评论列表
     *
     * @param userId 用户ID
     * @return API响应
     */
    public ApiResponse<List<Comment>> findByUserId(Long userId) {
        // 检查用户是否存在
        if (userMapper.findById(userId) == null) {
            throw new BusinessException("用户不存在");
        }

        List<Comment> comments = commentMapper.findByUserId(userId);
        return ApiResponse.success(comments);
    }

    /**
     * 根据专辑ID查询评论列表
     *
     * @param albumId 专辑ID
     * @return API响应
     */
    public ApiResponse<List<Comment>> findByAlbumId(Long albumId) {
        // 检查专辑是否存在
        if (albumMapper.findById(albumId) == null) {
            throw new BusinessException("专辑不存在");
        }

        List<Comment> comments = commentMapper.findByTargetIdAndType(albumId, "album");
        return ApiResponse.success(comments);
    }

    /**
     * 根据专辑ID分页查询评论列表
     *
     * @param albumId 专辑ID
     * @param pageRequest 分页请求
     * @return 分页响应
     */
    public PageResponse<Comment> findByAlbumIdWithPage(Long albumId, PageRequest pageRequest) {
        // 检查专辑是否存在
        if (albumMapper.findById(albumId) == null) {
            throw new BusinessException("专辑不存在");
        }

        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<Comment> comments = commentMapper.findByTargetIdAndTypeWithPage(albumId, "album", offset, pageRequest.getPageSize());
        Long total = commentMapper.countByTargetIdAndType(albumId, "album");

        // 构建分页响应
        return new PageResponse<>(comments, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();

            // 从自定义UserDetails中获取用户ID
            if (principal instanceof com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) {
                return ((com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) principal).getUserId();
            }

            // 尝试从请求属性中获取用户ID
            javax.servlet.http.HttpServletRequest request =
                    ((org.springframework.web.context.request.ServletRequestAttributes)
                            org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }

            throw new RuntimeException("无法获取用户ID");
        } catch (Exception e) {
            throw new RuntimeException("获取用户ID失败: " + e.getMessage());
        }
    }

    /**
     * 检查当前用户是否为管理员
     *
     * @return 是否为管理员
     */
    private boolean isAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
    }
}
